package per.chenxin.util.tcp.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketThread implements Runnable {

	ProxyEntity proxyEntity;

	Socket socketClient;

	Socket socketProxy;

	public SocketThread(Socket socketClient, ProxyEntity proxyEntity) {
		this.socketClient = socketClient;
		this.proxyEntity = proxyEntity;
		socketProxy = null;
	}

	public void run() {

		InputStream inputClient = null;
		OutputStream outputProxy = null;
		OutputStream outputClient = null;
		InputStream inputProxy = null;

		try {
			socketProxy = HttpUtil.getSocketFromProxy(proxyEntity);

			socketClient.setSoTimeout(1000);
			socketProxy.setSoTimeout(1000);
			inputClient = socketClient.getInputStream();
			outputProxy = socketProxy.getOutputStream();
			outputClient = socketClient.getOutputStream();
			inputProxy = socketProxy.getInputStream();

			while (true) {

				if (inputClient.available() > 0) {
					byte[] buffer = HttpUtil
							.getBytesFromInputStream(inputClient);
					outputProxy.write(buffer, 0, buffer.length);
					outputProxy.flush();
				}

				if (inputProxy.available() > 0) {
					byte[] buffer = HttpUtil
							.getBytesFromInputStream(inputProxy);
					outputClient.write(buffer, 0, buffer.length);
					outputClient.flush();
				}

				if (socketClient.isClosed() || socketClient.isInputShutdown()
						|| socketClient.isOutputShutdown())
					break;

				if (socketProxy.isClosed() || socketProxy.isInputShutdown()
						|| socketProxy.isOutputShutdown())
					break;

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		} catch (IOException ioe) {
		} finally {
			HttpUtil.close(inputClient);
			HttpUtil.close(outputProxy);
			HttpUtil.close(outputClient);
			HttpUtil.close(inputProxy);

		}

	}

	@Override
	protected void finalize() throws Throwable {

		if (socketClient != null)
			socketClient.close();
		socketClient = null;

		if (socketProxy != null)
			socketProxy.close();
		socketProxy = null;

		super.finalize();
	}

}
